# 存储入库单，同时更新物品库存信息
import sys
sys.path.append("..")
import json
from flask import request
from create_id import get_id
from db_client import *

def store_entry():
    # 存储入库单
    token = request.headers.get('token')
    flag, right = token_client.check_token(token)
    if not flag:
        t = {
            'state': 'false',
            'msg': '存储入库单失败'
        }
        return json.dumps(t, ensure_ascii=False)
    else:
        data = json.loads(request.get_data())
        entry_count = data['entry_count']
        entry_item_id = data['entry_item_id']
        entry_date = data['entry_date']
        order_id = data['order_id']
        storager_id = data['storager_id']
        _id = get_id('RK')

        flag2 = mysql_client.store_entry(_id, entry_count, entry_item_id, entry_date, order_id, storager_id)
        
        if flag2:
            t = {
                'state': 'true',
                'msg': 'success'
            }

            # 更新物品库存
            result = mysql_client.update_stock(entry_item_id, entry_count)
            if not result:
                t2 = {
                    'state': 'false',
                    'msg': '更新物品库存失败，稍后再试。'
                }
                return json.dumps(t2, ensure_ascii=False)

            return json.dumps(t, ensure_ascii=False)
        else:
            t = {
                'state': 'false',
                'msg': '提交入库单失败，稍后再试。'
            }
            return json.dumps(t, ensure_ascii=False)



